//
//  SGSProfileTableViewController.m
//  AgileNYC
//
//  Created by German on 02.08.14.
//  Copyright (c) 2014 Softlegion. All rights reserved.
//

#import "SGSProfileTableViewController.h"
#import "SGSUtils.h"
#import "SGSModelsManager.h"
#import "SGSDialogsManager.h"
#import "SGSAppConsts.h"
#import "SGSServerManagerConsts.h"
#import "SGSDelegatesManager.h"
#import "SGSAppDelegate.h"

@interface SGSProfileTableViewController () <UITextFieldDelegate, UITextViewDelegate, UIActionSheetDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate>

@property (assign, nonatomic) BOOL isProfileChanged;
@property (assign, nonatomic) BOOL isPhotoChanged;

@property (strong, nonatomic) UITextField * activeField;
@property (assign, nonatomic) UIEdgeInsets prevContentInsets;
@property (assign, nonatomic) UIEdgeInsets prevIndicatorInsets;

@property (strong, nonatomic) UIActivityIndicatorView * spinner;

@end

@implementation SGSProfileTableViewController

- (instancetype)init
{
    self = [super init];
    if (self) {
        GSLog(GSLogEvent, @"----- SGSProfileTableViewController inited");
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self markProfileChanges:NO];
    [self markPhotoChanges:NO];
    
    SGSDelegatesManager * delegatesManager = [SGSDelegatesManager sharedDelegatesManager];
    delegatesManager.currentProfileTableVC = self;
    
    self.isNewUser = delegatesManager.currentProfileVC.isNewUser;
    
    if (self.isNewUser) {
        [self markProfileChanges:YES];
        [self markPhotoChanges:YES];
    }
    
    self.edFirstName.delegate = self;
    self.edLastName.delegate = self;
    self.edEmail.delegate = self;
    self.edPhone.delegate = self;
    self.edTitle.delegate = self;
    self.edCompany.delegate = self;
    self.edWebSite.delegate = self;
    self.edCity.delegate = self;
    self.edState.delegate = self;
    self.edMemo.delegate = self;
    
    [self onProfileUpdate];
    [self onProfileImageUpdate:nil];
    

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onProfileUpdate) name:profileDidUpdateNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onProfileImageUpdate:) name:profileImageDidUpdateNotification object:nil];
    
    GSLog(GSLogEvent, @"----- SGSProfileTableViewController Did Load");

}

- (void)viewWillAppear:(BOOL)animated {
    [super viewDidAppear:animated];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onProfileUpdate) name:profileDidUpdateNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onProfileImageUpdate:) name:profileImageDidUpdateNotification object:nil];
    
    GSLog(GSLogEvent, @"----- GSProfileTableViewController Will Appear");
}


- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
    GSLog(GSLogEvent, @"----- GSProfileTableViewController Will Disappear");
}


#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 10;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [super tableView:tableView cellForRowAtIndexPath:indexPath];
    if (cell.hidden) {
        return 0;
    } else {
        return [super tableView:tableView heightForRowAtIndexPath:indexPath];
    }
}

#pragma mark - Internal Functions

-(BOOL) saveProfile {
    
    GSLog(GSLogInfo, @"[GSProfileTableViewController] Save button pressed");
    
    if (![self checkFirstName]) {
        return NO;
    }
    if (![self checkLastName]) {
        return NO;
    }
    if (![self checkEmail]) {
        return NO;
    }
    
    [self.edLastName resignFirstResponder];
    [self.edEmail resignFirstResponder];
    [self.edEmail resignFirstResponder];
    [self.edPhone resignFirstResponder];
    [self.edTitle resignFirstResponder];
    [self.edCompany resignFirstResponder];
    [self.edWebSite resignFirstResponder];
    [self.edCity resignFirstResponder];
    [self.edState resignFirstResponder];
    [self.edMemo resignFirstResponder];
    [self.edMemo resignFirstResponder];

    
    GSUser * currentUser = [[SGSModelsManager sharedModelsManager] currentUser];
    SGSModelsManager * modelsManager = [SGSModelsManager sharedModelsManager];
    
    __weak __typeof(self) weakSelf = self;
    
    // Make the block for user saving data after creation
    void (^completitionBlock)(BOOL,NSError*) = ^(BOOL result, NSError *error) {
        
        __strong typeof(self)self = weakSelf;
        
        if (result) {
            self.isNewUser = NO;

            [self saveUserData];
        } else {
            [[SGSDialogsManager dialogsManager] showSimpleDialog:Error_Dialog_Title message:[error domain] onComplete:nil];
        }
    };
    
    //Save user data (check for new user before)
    if (self.isNewUser) { //It's a new user
        
        if (currentUser.socialType==GSEmailLoginType) {
            [modelsManager createUserWithEmail:self.edEmail.text
                                      password:currentUser.password
                                    onComplete:completitionBlock];
            
        } else {
            GSLog(GSLogInfo, @"Social type: %d", currentUser.socialType);
            [modelsManager createUserWithSocial:self.edEmail.text
                                     socialType:(GSLoginType)currentUser.socialType
                                     onComplete:completitionBlock];
        }
    } else {
        [self saveUserData];
    }
    
    return YES;
}

-(void) loadDataToControls
{
    SGSModelsManager * modelsManager = [SGSModelsManager sharedModelsManager];
    GSUser * currentUser = [modelsManager currentUser];
    
    self.edFirstName.text       = currentUser.firstName;
    self.edLastName.text        = currentUser.lastName;
    self.edEmail.text           = currentUser.eMail;
    self.edTitle.text           = currentUser.title;
    self.edCompany.text         = currentUser.company;
    self.edWebSite.text         = currentUser.webSite;
    self.edCity.text            = currentUser.city;
    self.edState.text           = currentUser.state;
    self.edMemo.text            = currentUser.memo;
    
    NSString * formattedPhoneNumber = getFormattedPhoneNumber(currentUser.phone);
    
    if (formattedPhoneNumber) {
        self.edPhone.text = formattedPhoneNumber;
    }

}

-(void) loadPhotoToControl {
    SGSModelsManager * modelsManager = [SGSModelsManager sharedModelsManager];
    GSUser * currentUser = [modelsManager currentUser];
    
    [self.spinnerPhoto startAnimating];

    self.imgPhoto.image = nil;
    //[modelsManager requestImageForContactByContact:currentUser loadToImageView:self.imgPhoto];
    [modelsManager requestImageForContactByContact:currentUser onComplete:^(BOOL result, UIImage *image) {
        if (result) {
            self.imgPhoto.image = image;
            self.imgNoPhoto.hidden = YES;
        } else {
            self.imgPhoto.image = nil;
            self.imgNoPhoto.hidden = NO;
        }
        [self.spinnerPhoto stopAnimating];
    }];
}

-(void) updateSocialNetworksButtons {
    __block GSUser * currentUser = [[SGSModelsManager sharedModelsManager] currentUser];
    
    if ((currentUser.facebookId) && ([currentUser.facebookId length]>0)) {
        self.btnDisconnectFromFacebook.hidden = NO;
        self.imgDisconnectFromFacebook.hidden = NO;
        if ([[currentUser.facebookName stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length]>0) {
            [self.btnConnectToFacebook setTitle:currentUser.facebookName forState:UIControlStateNormal];
        } else if ([[currentUser fullName] length]>0) {
            [self.btnConnectToFacebook setTitle:[currentUser fullName] forState:UIControlStateNormal];
        } else {
            [self.btnConnectToFacebook setTitle:currentUser.facebookId forState:UIControlStateNormal];
        }
    } else {
        self.btnDisconnectFromFacebook.hidden = YES;
        self.imgDisconnectFromFacebook.hidden = YES;

        [self.btnConnectToFacebook setTitle:Connect_To_Facebook_Button_Text forState:UIControlStateNormal];
    }
    
    if ((currentUser.googlePlusId) && ([currentUser.googlePlusId length]>0)) {
        self.btnDisconnectFromGooglePlus.hidden = NO;
        self.imgDisconnectFromGooglePlus.hidden = NO;
        if ([[currentUser.googlePlusName stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length]>0) {
            [self.btnConnectToGooglePlus setTitle:currentUser.googlePlusName forState:UIControlStateNormal];
        } else if ([[currentUser fullName] length]>0) {
            [self.btnConnectToFacebook setTitle:[currentUser fullName] forState:UIControlStateNormal];
        } else {
            [self.btnConnectToFacebook setTitle:currentUser.googlePlusId forState:UIControlStateNormal];
        }
    } else {
        self.btnDisconnectFromGooglePlus.hidden = YES;
        self.imgDisconnectFromGooglePlus.hidden = YES;
        [self.btnConnectToGooglePlus setTitle:Connect_To_GooglePlus_Button_Text forState:UIControlStateNormal];
    }
    
    if ((currentUser.linkedInId) && ([currentUser.linkedInId length]>0)) {
        dispatch_async(dispatch_get_main_queue(), ^{ //I did it because it wouldn't update imidiatelly. I think it threads problems
            self.btnDisconnectFromLinkedIn.hidden = NO;
            self.imgDisconnectFromLinkedIn.hidden = NO;
            if ([[currentUser.linkedInName stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length]>0) {
                [self.btnConnectToLinkedIn setTitle:currentUser.linkedInName forState:UIControlStateNormal];
            } else if ([[currentUser fullName] length]>0) {
                [self.btnConnectToFacebook setTitle:[currentUser fullName] forState:UIControlStateNormal];
            } else {
                [self.btnConnectToFacebook setTitle:currentUser.linkedInId forState:UIControlStateNormal];
            }
        });
    } else {
        self.btnDisconnectFromLinkedIn.hidden = YES;
        self.imgDisconnectFromLinkedIn.hidden = YES;
        [self.btnConnectToLinkedIn setTitle:Connect_To_LinkedIn_Button_Text forState:UIControlStateNormal];
    }
}

-(void) updateProfilePhoto { //Чтобы не обновлять все поля

    [self.spinnerPhoto stopAnimating];
    
    GSUser * currentUser = [[SGSModelsManager sharedModelsManager] currentUser];
    
    if (currentUser.photo) {
        self.imgNoPhoto.hidden = YES;
        self.imgPhoto.image  = [currentUser getPhotoAsImage];
    } else {
        self.imgNoPhoto.hidden = NO;
        self.imgPhoto.image  = nil;
    }
}

-(void) saveUserData {
    
    SGSModelsManager * modelsManager = [SGSModelsManager sharedModelsManager];
    
    GSUser * loginUser = modelsManager.currentUser;
    
    if (self.isProfileChanged) {
        
        NSDictionary * newUserDataDict = [NSDictionary dictionaryWithObjectsAndKeys:
          self.edFirstName.text         ,   userFirstNameKey,
          self.edLastName.text          ,   userLastNameKey,
          self.edEmail.text             ,   userEmailKey,
          self.edPhone.text             ,   userPhoneKey,
          self.edTitle.text             ,   userTitleKey,
          self.edCompany.text           ,   userCompanyNameKey,
          self.edWebSite.text           ,   userWebSiteKey,
          self.edCity.text              ,   userCityKey,
          self.edState.text             ,   userStateKey,
          self.edMemo.text              ,   userMemoKey,
          nil];
        
        [modelsManager saveUserChangesAndSendToServer:loginUser newUserData:newUserDataDict onComplete:nil];
    }
    
    if (self.isPhotoChanged) {
        if (self.imgPhoto.image) {
            [modelsManager saveUserImageAndSendToServer:self.imgPhoto.image forUser:loginUser];
            GSLog(GSLogInfo, @"[saveUserData] saveUserImageAndSendToServer");
        } else {
            [modelsManager deleteUserImageAndSendToServer:loginUser];
            GSLog(GSLogInfo, @"[saveUserData] deleteUserImageAndSendToServer");
        }
    }
}

#pragma mark - Actions

- (IBAction)onConnectToFacebookButtonClick:(UIButton *)sender {
    GSUser * loginUser = [SGSModelsManager sharedModelsManager].currentUser;
    SGSModelsManager * modelsManager = [SGSModelsManager sharedModelsManager];
    
    GSLog(GSLogInfo, @"[onConnectToFacebookButtonClick] button pressed");
    
    __weak __typeof(self) weakSelf = self;
    
    if ((loginUser.facebookId) && ([loginUser.facebookId length]>0)) {
        
        NSString *url = [NSString stringWithFormat:@"https://facebook.com/%@",loginUser.facebookId];
        url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        
        if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:url]]){
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];
        }
        else {
            url = [NSString stringWithFormat:@"https://facebook.com/%@",loginUser.facebookId];
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];
        }
        
    } else {
        
        //[self  startSpinnerOnView:self.imgFacebook];
        [self.spinnerFacebook startAnimating];
        self.btnConnectToFacebook.enabled = NO;
        
        if (!loginUser.photo) {
            [modelsManager updateIdAndImageFromFacebookForCurrentUser:^(BOOL result) {
                
                __strong typeof(self)self = weakSelf;
                
                if (result) {
                    [self updateSocialNetworksButtons];
                }
                
                GSLog(GSLogWarning, @"[onConnectToFacebookButtonClick] Facebook profile and photo updated");

                [self.spinnerFacebook stopAnimating];
                self.btnConnectToFacebook.enabled = YES;
                
                [self markProfileChanges:YES];
                
                [self markPhotoChanges:YES];
            }];
        } else {
            [modelsManager updateIdFromFacebookForCurrentUser:^(BOOL result) {

                __strong typeof(self)self = weakSelf;
                
                if (result) {
                    [self updateSocialNetworksButtons];
                }
                
                GSLog(GSLogInfo, @"[onConnectToFacebookButtonClick] Facebook profile updated");
                
                [self.spinnerFacebook stopAnimating];
                self.btnConnectToFacebook.enabled = YES;
                
                [self markProfileChanges:YES];
                
            }];
        }
    }
}

- (IBAction)onConnectToLinkedInButtonClick:(UIButton *)sender {
    GSUser * loginUser = [SGSModelsManager sharedModelsManager].currentUser;
    SGSModelsManager * modelsManager = [SGSModelsManager sharedModelsManager];
    
    __weak __typeof(self) weakSelf = self;
    
    GSLog(GSLogInfo, @"[onConnectToLinkedInButtonClick] button pressed");
    
    if ((loginUser.linkedInId) && ([loginUser.linkedInId length]>0)) {
        
        NSString *url = [NSString stringWithFormat:@"%@",loginUser.linkedInId];
        
        url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];
        
    } else {
        
        [self.spinnerLinkedIn startAnimating];
        self.btnConnectToLinkedIn.enabled = NO;
        
        if (!loginUser.photo) {
            [modelsManager updateIdAndImageFromLinkedInForCurrentUser:^(BOOL result) {
                GSLog(GSLogInfo, @"LinkedIn login: %@", [NSNumber numberWithBool:result]);
                
                __strong typeof(self)self = weakSelf;
                
                if (result) {
                    [self updateSocialNetworksButtons];
                }
                
                GSLog(GSLogWarning, @"[onConnectToLinkedInButtonClick] LinkedIn profile and photo updated");
                
                [self.spinnerLinkedIn stopAnimating];
                self.btnConnectToLinkedIn.enabled = YES;
                
                [self markProfileChanges:YES];
                [self markPhotoChanges:YES];
            }];
        } else {
            [modelsManager updateIdFromLinkedInForCurrentUser:^(BOOL result) {
                GSLog(GSLogInfo, @"LinkedIn login: %@", [NSNumber numberWithBool:result]);
                
                __strong typeof(self)self = weakSelf;
                
                if (result) {
                    [self updateSocialNetworksButtons];
                }
                
                GSLog(GSLogInfo, @"[onConnectToLinkedInButtonClick] LinkedIn profile updated");
                
                [self.spinnerLinkedIn stopAnimating];
                self.btnConnectToLinkedIn.enabled = YES;
                
                [self markProfileChanges:YES];
            }];
        }
    }
}

- (IBAction)onConnectToGooglePlusButtonClick:(UIButton *)sender {
    GSUser * loginUser = [SGSModelsManager sharedModelsManager].currentUser;
    SGSModelsManager * modelsManager = [SGSModelsManager sharedModelsManager];
    
    __weak __typeof(self) weakSelf = self;
    
    GSLog(GSLogInfo, @"[onConnectToGooglePlusButtonClick] button pressed");
    
    if ((loginUser.googlePlusId) && ([loginUser.googlePlusId length]>0)) {
        
        NSString *url = [NSString stringWithFormat:@"https://plus.google.com/%@",loginUser.googlePlusId];
        
        url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];
        
    } else {
        
        [self.spinnerGooglePlus startAnimating];
        self.btnConnectToGooglePlus.enabled = NO;

        if(!loginUser.photo) {
            [modelsManager updateIdAndImageFromGooglePlusForCurrentUser:^(BOOL result) {
                
                __strong typeof(self)self = weakSelf;
                
                if (result) {
                    [self updateSocialNetworksButtons];
                }
                
                GSLog(GSLogWarning, @"[onConnectToGooglePlusButtonClick] Google profile and photo updated");
                
                [self.spinnerGooglePlus stopAnimating];
                self.btnConnectToGooglePlus.enabled = YES;

                [self markProfileChanges:YES];
                [self markPhotoChanges:YES];
            }];
        } else {
            [modelsManager updateIdFromGooglePlusForCurrentUser:^(BOOL result) {
                
                __strong typeof(self)self = weakSelf;
                
                if (result) {
                    [self updateSocialNetworksButtons];
                }
                
                GSLog(GSLogInfo, @"[onConnectToGooglePlusButtonClick] Google profile updated");
                
                [self.spinnerGooglePlus stopAnimating];
                self.btnConnectToGooglePlus.enabled = YES;
                
                [self markProfileChanges:YES];
            }];
        }
    }
}

- (IBAction)onDisconnectFromFacebookButtonClick:(UIButton *)sender {
    
    SGSModelsManager * modelsManager = [SGSModelsManager sharedModelsManager];
    __weak __typeof(self) weakSelf = self;

    [modelsManager clearIdForFacebookForCurrentUser:^(BOOL result) {
        
        __strong typeof(self)self = weakSelf;
        
        if (result) {
            [self updateSocialNetworksButtons];
        }
        
        GSLog(GSLogWarning, @"[onConnectToFacebookButtonClick] Facebook profile cleared");
        
        [self markProfileChanges:YES];
    }];
}

- (IBAction)onDisconnectFromGooglePlusButtonClick:(UIButton *)sender {
    
    SGSModelsManager * modelsManager = [SGSModelsManager sharedModelsManager];
    __weak __typeof(self) weakSelf = self;

    [modelsManager clearIdForGooglePlusForCurrentUser:^(BOOL result) {
        
        __strong typeof(self)self = weakSelf;
        
        if (result) {
            [self updateSocialNetworksButtons];
        }
        
        GSLog(GSLogWarning, @"[onConnectToGooglePlusButtonClick] Google profile cleared");
        
        [self markProfileChanges:YES];
    }];
}

- (IBAction)onDisconnectFromLinkedInButtonClick:(UIButton *)sender {
    SGSModelsManager * modelsManager = [SGSModelsManager sharedModelsManager];
    __weak __typeof(self) weakSelf = self;

    [modelsManager clearIdForLinkedInForCurrentUser:^(BOOL result) {
        
        __strong typeof(self)self = weakSelf;
        
        if (result) {
            [self updateSocialNetworksButtons];
        }
        
        GSLog(GSLogWarning, @"[onConnectToLinkedInButtonClick] LinkedIn profile cleared");
        
        [self markProfileChanges:YES];
    }];
}

#pragma mark - Notifications

-(void) onProfileUpdate {
    
    [self loadDataToControls];
    [self updateSocialNetworksButtons];
    
}

-(void) onProfileImageUpdate:(NSNotification*)notification {
    GSLog(GSLogInfo, @"[SGSProfileTableViewController] Notification received: %@",profileImageDidUpdateNotification);
    
    NSDictionary* info = [notification userInfo];
    
    if (info) {
        return; //It means that it is updating of contacts
    }
    
    //[self updateProfilePhoto];
    [self loadPhotoToControl];
    [self updateProfilePhoto];
    
    self.imgPhoto.alpha = 0;
    [UIView animateWithDuration:0.5f
                          delay:0
                        options:UIViewAnimationOptionCurveEaseInOut
                     animations:^{
                         self.imgPhoto.alpha = 1;
                     }
                     completion:nil];
    
}

#pragma mark - UITextFieldDelegate

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    self.activeField = textField;
}

- (void)textFieldDidEndEditing:(UITextField *)textField
{
    self.activeField = nil;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    
    if ([textField isEqual:self.edFirstName]) {
        [self.edLastName becomeFirstResponder];
    } else if ([textField isEqual:self.edLastName]) {
        [self.edEmail becomeFirstResponder];
    } else if ([textField isEqual:self.edLastName]) {
        [self.edEmail becomeFirstResponder];
    } else if ([textField isEqual:self.edEmail]) {
        [self.edPhone becomeFirstResponder];
    } else if ([textField isEqual:self.edPhone]) {
        [self.edTitle becomeFirstResponder];
    } else if ([textField isEqual:self.edTitle]) {
        [self.edCompany becomeFirstResponder];
    } else if ([textField isEqual:self.edCompany]) {
        [self.edWebSite becomeFirstResponder];
    } else if ([textField isEqual:self.edWebSite]) {
        [self.edCity becomeFirstResponder];
    } else if ([textField isEqual:self.edCity]) {
        [self.edState becomeFirstResponder];
    } else if ([textField isEqual:self.edState]) {
        [self.edMemo becomeFirstResponder];
    } else if ([textField isEqual:self.edMemo]) {
        [self.edMemo resignFirstResponder];
    }
    
    return YES;
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    
    [self markProfileChanges:YES];
    
    if ([textField isEqual:self.edPhone]) {
        NSCharacterSet * validatingSet = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
        NSArray * components = [string componentsSeparatedByCharactersInSet:validatingSet];
        
        if ([components count] >1 ) {
            return NO;
        }
        
        NSString * newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
        GSLog(GSLogInfo, @"New phone string: %@", newString);
        
        NSString * newPhoneNumber = getFormattedPhoneNumber(newString);
        
        if (newPhoneNumber) {
            textField.text = newPhoneNumber;
        }
        
        return NO;
    }
    
    return YES;
}

- (BOOL)textFieldShouldClear:(UITextField *)textField {
    
    [self markProfileChanges:YES];
    
    return YES;
}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
    [self markProfileChanges:YES];
    
    return YES;
}

-(void) markProfileChanges:(BOOL) changeIndicator {
    self.isProfileChanged = changeIndicator;
    
    if (changeIndicator) {
        [[SGSDelegatesManager sharedDelegatesManager].currentProfileVC setBackButtonCaption:Save_Button_Text];
    } else {
        [[SGSDelegatesManager sharedDelegatesManager].currentProfileVC setBackButtonCaption:Back_Button_Text];
    }
    
}

-(void) markPhotoChanges:(BOOL) changeIndicator {
    self.isPhotoChanged = changeIndicator;
    
    if (changeIndicator) {
        [[SGSDelegatesManager sharedDelegatesManager].currentProfileVC setBackButtonCaption:Save_Button_Text];
    } else {
        [[SGSDelegatesManager sharedDelegatesManager].currentProfileVC setBackButtonCaption:Back_Button_Text];
    }
}

#pragma mark - UIActionSheetDelegate

- (IBAction)btnChangePhoto:(id)sender {
    NSString * deleteButtonCaption;
    
    GSLog(GSLogInfo, @"[btnChangePhoto] button pressed");
    //GSUser * loginUser = [SGSModelsManager sharedModelsManager].currentUser;
    
    //if (self.isPhotoExisting) {
    if (self.imgPhoto.image) {
        deleteButtonCaption = Delete_Profile_Photo_Button_Titile;
    } else {
        deleteButtonCaption = nil;
    }
    
    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:nil
                                                             delegate:self
                                                    cancelButtonTitle:Cancel_Button_Title
                                               destructiveButtonTitle:deleteButtonCaption
                                                    otherButtonTitles:Take_Photo_From_Camera_Button_Titile,
                                  Select_Photo_From_Galary_Button_Titile,
                                  nil];
    
    [actionSheet showInView:self.view];
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (!self.picker) {
        self.picker = [[UIImagePickerController alloc] init];
        self.picker.delegate = self;
        self.picker.mediaTypes = @[(NSString *) kUTTypeImage];
        self.picker.allowsEditing = YES;
    }
    
    if ([[actionSheet buttonTitleAtIndex:buttonIndex] isEqualToString:Delete_Profile_Photo_Button_Titile]) {
        
        self.imgPhoto.image = nil;
        self.imgNoPhoto.hidden = NO;
        [self markPhotoChanges:YES];
        
        GSLog(GSLogWarning, @"[actionSheet] Clear Picture selected");
    }
    
    if ([[actionSheet buttonTitleAtIndex:buttonIndex] isEqualToString:Take_Photo_From_Camera_Button_Titile]) {
        
        if ([UIImagePickerController isSourceTypeAvailable:
             UIImagePickerControllerSourceTypeCamera])
        {
            self.picker.sourceType = UIImagePickerControllerSourceTypeCamera;
            [self presentViewController:self.picker animated:YES completion:^{}];
        } else {
            UIAlertView * av = [[UIAlertView alloc] initWithTitle:Camera_is_not_available_Title
                                                          message: Camera_is_not_available_Message
                                                         delegate:nil
                                                cancelButtonTitle:Ok_Button_Title
                                                otherButtonTitles:nil];
            [av show];
        }
    }
    
    if ([[actionSheet buttonTitleAtIndex:buttonIndex] isEqualToString:Select_Photo_From_Galary_Button_Titile]) {
        if ([UIImagePickerController isSourceTypeAvailable:
             UIImagePickerControllerSourceTypePhotoLibrary])
        {
            self.picker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
            [self presentViewController:self.picker animated:YES completion:^{}];
        } else {
            UIAlertView * av = [[UIAlertView alloc] initWithTitle:Galary_is_not_available_Title
                                                          message: Galary_is_not_available_Message
                                                         delegate:nil
                                                cancelButtonTitle:Ok_Button_Title
                                                otherButtonTitles:nil];
            [av show];
        }
    }
    
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    
    NSString *mediaType = info[UIImagePickerControllerMediaType];
    
    if ([mediaType isEqualToString:(NSString *)kUTTypeImage])
    {
        self.imgNoPhoto.hidden = YES;
        self.imgPhoto.image = (UIImage*)[info objectForKey:UIImagePickerControllerEditedImage];
        [self markPhotoChanges:YES];
        
        GSLog(GSLogInfo,@"[imagePickerController] image loaded");
    }
    else if ([mediaType isEqualToString:(NSString *)kUTTypeMovie])
    {
        // Media is a video
    }
    
    
    [self.picker dismissViewControllerAnimated:YES completion:^{}];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [self.picker dismissViewControllerAnimated:YES completion:^{}];
}

#pragma mark - Spinner

-(void) startSpinner {
    
    SGSAppDelegate * appDelegate = [UIApplication sharedApplication].delegate;
    [appDelegate startSpinner];
    
}

-(void) stopSpinner {
    
    SGSAppDelegate * appDelegate = [UIApplication sharedApplication].delegate;
    [appDelegate stopSpinner];
}

#pragma mark - Notifications

- (void)keyboardWillShow:(NSNotification*)notification {
    GSLog(GSLogInfo,@"[GSProfileTableViewController] Keyboard will show");
    
    NSDictionary* info = [notification userInfo];
    CGSize kbSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
    
    self.prevContentInsets = self.tbProfileTableView.contentInset;
    self.prevIndicatorInsets = self.tbProfileTableView.scrollIndicatorInsets;
    
    UIEdgeInsets newContentInsets = UIEdgeInsetsMake(self.tbProfileTableView.contentInset.top,
                                                     self.tbProfileTableView.contentInset.left,
                                                     kbSize.height,
                                                     self.tbProfileTableView.contentInset.right);
    UIEdgeInsets newIndicatorInsets = UIEdgeInsetsMake(self.tbProfileTableView.contentInset.top,
                                                       self.tbProfileTableView.contentInset.left,
                                                       kbSize.height,
                                                       self.tbProfileTableView.contentInset.right);
    
    self.tbProfileTableView.contentInset = newContentInsets;
    self.tbProfileTableView.scrollIndicatorInsets = newIndicatorInsets;
    
    // If active text field is hidden by keyboard, scroll it so it's visible
    // Your app might not need or want this behavior.
    CGRect aRect = self.view.frame;
    aRect.size.height -= kbSize.height;
    if (!CGRectContainsPoint(aRect, self.activeField.frame.origin) ) {
        [self.self.tbProfileTableView scrollRectToVisible:self.activeField.frame animated:YES];
    }
}

- (void)keyboardWillHide:(NSNotification*)notification {
    GSLog(GSLogInfo,@"[GSProfileTableViewController] Keyboard will hide");
    
    self.tbProfileTableView.contentInset = self.prevContentInsets;
    self.tbProfileTableView.scrollIndicatorInsets = self.prevIndicatorInsets;
    
    
}

#pragma mark - Spinner

-(void) startSpinnerOnView:(UIView*) view {
    
   self.spinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
   
   self.spinner.frame = view.frame;
   self.spinner.center = view.center;
    
   GSLog(GSLogInfo, @"%f %f", self.spinner.frame.origin.x, self.spinner.frame.origin.y);
   GSLog(GSLogInfo, @"%f %f", view.frame.origin.x, view.frame.origin.y);
    
   [view addSubview:self.spinner];
    
   [self.spinner startAnimating];
        
}

#pragma mark - Mandatory fields check

-(BOOL) checkEmail {

    if ([[self.edEmail.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length]==0) {
        
        self.edEmail.backgroundColor = COLOR_MAIN_WHITE;
        
        [[SGSDialogsManager dialogsManager] showSimpleDialog:Error_Dialog_Title message:Email_Is_Empty_Message onComplete:^{
            [self.edEmail becomeFirstResponder];
            [UIView animateWithDuration:1.0f
                                  delay:1.0f
                                options:UIViewAnimationOptionCurveEaseInOut
                             animations:^{
                                 self.edEmail.backgroundColor = COLOR_MAIN_BLUE;
                             }
                             completion:nil];
        }];
        return NO;
    }
    
    return YES;
}


-(BOOL) checkFirstName {
    
    if ([[self.edFirstName.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length]==0) {
        
        self.edFirstName.backgroundColor = COLOR_MAIN_WHITE;
        
        [[SGSDialogsManager dialogsManager] showSimpleDialog:Error_Dialog_Title message:FirstName_Is_Empty_Message onComplete:^{
            [self.edFirstName becomeFirstResponder];
            [UIView animateWithDuration:1.0f
                                  delay:1.0f
                                options:UIViewAnimationOptionCurveEaseInOut
                             animations:^{
                                 self.edFirstName.backgroundColor = COLOR_MAIN_BLUE;
                             }
                             completion:nil];
        }];
        return NO;
    }

    return YES;
}

-(BOOL) checkLastName {

    if ([[self.edLastName.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length]==0) {
        
        self.edLastName.backgroundColor = COLOR_MAIN_WHITE;
        
        [[SGSDialogsManager dialogsManager] showSimpleDialog:Error_Dialog_Title message:LastName_Is_Empty_Message onComplete:^{
            [self.edLastName becomeFirstResponder];
            [UIView animateWithDuration:1.0f
                                  delay:1.0f
                                options:UIViewAnimationOptionCurveEaseInOut
                             animations:^{
                                 self.edLastName.backgroundColor = COLOR_MAIN_BLUE;
                             }
                             completion:nil];
        }];
        return NO;
    }
    
    return YES;
    
}

#pragma mark - System Functions

- (void)didReceiveMemoryWarning {[super didReceiveMemoryWarning];}

@end
